package com.alm.handle.service.impl.apiimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alm.api.EleTaskService;
import com.alm.common.constant.CacheConstants;
import com.alm.common.core.redis.RedisCache;
import com.alm.handle.core.domain.entity.SysDevCurrentData;
import com.alm.handle.core.domain.entity.SysDevCurrentData_s;
import com.alm.handle.core.domain.entity.SysDevInfo;
import com.alm.handle.core.domain.entity.rq.GetWayInfoRq;
import com.alm.handle.core.domain.entity.rs.SysDevCurrentDataRS;
import com.alm.handle.core.domain.entity.vo.CurrentVo;
import com.alm.handle.mapper.SysDevCurrentDataMapper;
import com.alm.handle.mapper.SysDevCurrentData_sMapper;
import com.alm.handle.mapper.SysDevInfoMapper;
import com.alm.handle.service.ISysDevCurrentDataService;
import com.alm.handle.service.ISysDevHistoryInfoService;
import com.alm.handle.service.SysAlmEventsLogService;
import com.alm.handle.util.ELeCurrentUtil;
import com.alm.handle.util.SoketEleKey;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

@Service
public class EleTaskServiceImpl implements EleTaskService {
    private static final Logger log = LoggerFactory.getLogger(EleTaskServiceImpl.class);
    @Autowired
    SysDevCurrentDataMapper currentDataMapper;
    @Resource
    SysDevInfoMapper devInfoMapper;
    @Autowired
    ISysDevCurrentDataService dataService;
    @Autowired
    RedisCache redisCache;
    @Autowired
    ISysDevHistoryInfoService historyInfoService;
    @Autowired
    SysAlmEventsLogService eventsLogService;
    @Override
    public void resetOnlieStatus() {
        //查询在线的设备  只针对插座
        QueryWrapper queryWrapper=new QueryWrapper();
        SysDevInfo sysDevInfo=new SysDevInfo();
        sysDevInfo.setOnlineStatus(0);
        List<SysDevCurrentDataRS> list=  currentDataMapper.findOnlineDev();
        if(list!=null&& list.size()>0){
            for (SysDevCurrentDataRS currentData:list){
                String key= SoketEleKey.ON_LINE+currentData.getDeviceId();
                if(!redisCache.hasKey(key)){
                    queryWrapper.eq("device_id",currentData.getDeviceId());
                    devInfoMapper.update(sysDevInfo,queryWrapper);
                    dataService.flushPersistenceByMac(currentData.getDeviceId());
                    //离线
                    Integer id= eventsLogService.isnertLog(currentData.getDeviceId(),2);
                    eventsLogService.upexistTime(currentData.getDeviceId(),2,id);
                    eventsLogService.upexistTime(currentData.getDeviceId(),5,0);
                    redisCache.deleteObject(SoketEleKey.EX_ENERY+currentData.getDeviceId());

                }
            }
        }
        GetWayInfoRq getWayInfoRq=new GetWayInfoRq();
        getWayInfoRq.setOnlineStatus(1);
        getWayInfoRq.setIsAdmin(true);
        List<SysDevInfo> list1=  devInfoMapper.queryByGetWay(getWayInfoRq);
        if(list!=null&& list.size()>0){
            for (SysDevInfo devInfo:list1){
                String key= SoketEleKey.ON_LINE+devInfo.getDeviceId();
                if(!redisCache.hasKey(key)){
                    //置为离线
                    queryWrapper.eq("device_id",devInfo.getDeviceId());
                    devInfoMapper.update(sysDevInfo,queryWrapper);
                    //应该删除数据
                    String sort_key= SoketEleKey.GW_ELE_ZSET+devInfo.getDeviceId();
                    String data_key= SoketEleKey.GW_ELE_DATA+devInfo.getDeviceId();
                  //  redisCache.deleteObject(sort_key);
                   // redisCache.deleteObject(data_key);
                }
            }
        }
    }

    @Override
    public void saveHis() {
        Set<String> set = redisCache.getCacheSet(SoketEleKey.SAVE_HIS);
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        int day = currentDate.getDayOfMonth();
        if(set!=null){
            for (String mac:set){
                String redisDataKey= SoketEleKey.ELE_DATA+mac;
                if(redisCache.hasKey(redisDataKey)){
                    String redisData=redisCache.getCacheObject(redisDataKey);
                    CurrentVo currentVo= JSON.parseObject(redisData,CurrentVo.class);
                    currentVo.setYear(year);
                    currentVo.setMonth(month);
                    currentVo.setDay(day);
                    currentVo.setEnergy(getEnrgy(mac,new BigDecimal(currentVo.getEnergy())));
                    historyInfoService.insertHistory(currentVo);
                }
            }
        }
    }

    @Override
    public void flushPersistence() {
        dataService.flushPersistenceAll();
    }

    @Override
    public void autoGenerationELHis() {
        dataService.autoGenerationELHis();
    }

    @Override
    public void autoGenerationELByAreaHis() {
        dataService.autoGenerationELHis();
    }

    private Double getEnrgy(String devmac, BigDecimal newenery){
        if(newenery==null){
            log.info("sava hisData errer  enert is null");
            return 0d;
        }
        BigDecimal enery= redisCache.getCacheMapValue(SoketEleKey.HIS_ENERY,devmac);
        if(enery==null){
            enery=newenery.setScale(4,BigDecimal.ROUND_CEILING);
        }else{
            enery=newenery.subtract(enery).setScale(4,BigDecimal.ROUND_CEILING);
        }
        redisCache.setCacheMapValue(SoketEleKey.HIS_ENERY,devmac,newenery.setScale(4,BigDecimal.ROUND_CEILING));
        return enery.doubleValue();
    }
}
